var appServices = angular.module('starter.services', [])
    .factory('HostConfig', function () {
        // var _API = 'https://api.kakanet.net/card/am';
        // var _smsAPI = 'https://api.youfansoft.com/yfcrm/am';
        // var _API = 'http://127.0.0.1:8080/mall/am/interfaceController';
        //  var _API = 'http://10.0.0.4:8080/am/interfaceController';
        // var _API = 'http://192.168.43.169:8081/am/interfaceController';//无限网本机
        // var _API = 'https://shcrapp.promni.cn/mall/am/interfaceController';//世纪汇  
        // var _API = 'http://mall.youfansoft.com/mall/am/interfaceController';//测试服
        var _API = 'https://api.sh-centurylink.cn/mall/am/interfaceController';
        return {
            getAPI: function (host) {
                return host || _API;
            },
            getSmsAPI: function (host) {
                return host || _smsAPI;
            }
        };
    })
    .factory('Logger', function () {
        return {
            log: function (msg) {
                console.log(msg);
            },
            error: function (msg) {
                console.error(msg);
            },
            warn: function (msg) {
                console.warn(msg);
            }
        }
    })
   
    // .factory('/', function ($ionicHistory, $state, jPush, umengAnalytics, Storage) {
    .factory('ionPlugins', function ($ionicHistory, $state,  Storage){
        return {
            // init: function () {
            //     jPush.init(); // 初始化推送
            //     umengAnalytics.init(); // 初始化友盟统计配置
            //     console.log('jPush and umengAnalytics init');
            // },
            // 保存用户数据
            save_user_data: function (_data) {
                // return console.log(JSON.stringify(_data));
                // jPush.setAlias('alias_' + _data.user.user_id);
                Storage.ls_set('user_id', _data.user.user_id);
                Storage.ls_set('user_login_name', _data.user.user_login_name);
                Storage.ls_set('user_name', _data.user.user_name);
                Storage.ls_set('user_login_mobile', _data.user.user_login_mobile);
                Storage.ls_set('user_token', _data.jwt);
                Storage.ls_set('user_login_time', new Date().getTime()); // 存储登录时间
                // return console.log( _data.user.user_id);
                // return console.log("111"+JSON.stringify($ionicHistory.clearCache()));
                $ionicHistory.clearCache().then(function () {
                    var a = $ionicHistory.viewHistory();
                    $state.go('tab.home');
                    // return console.log( JSON.stringify(a));
                })
                // return console.log(Storage.ls_get("user_token")+"+"+Storage.ls_get('user_login_time'));
            },
            // 删除用户数据
            delete_user_data: function () {
                // jPush.setAlias('');
                Storage.ls_delete('user_token');
                Storage.ls_delete('user_id');
                Storage.ls_delete('user_login_name');
                Storage.ls_delete('user_name');
                Storage.ls_delete('user_login_mobile');
                Storage.ls_delete('user_login_time');
                $ionicHistory.clearHistory();
                $state.go('login');
            },
            // group_setTags: function (_group_number) {
            //     jPush.setTags(['tag_' + _group_number]);
            // },
            // group_delTags: function () {
            //     jPush.setTags([]);
            // }
        }
    })
   
    // .factory('Common', function ($state, $interval, ionNative) {
    .factory('Common', function ($state, $interval, ionNative) {
        var mobile = /^\d{5,}$/, // var mobile = /^1(3|4|5|7|8)[0-9]\d{8}$/,
            telephone = /^0\d{2,3}-?\d{7,8}$/,
            email = /\w[-\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\.)+[A-Za-z]{2,14}/,
            fax = /^(\d{3,4}-)?\d{7,8}$/,
            alertPopup;
        return {
            isMobile: function (_mobileNumber) {
                return mobile.test(_mobileNumber)
            },
            isEmail: function (_emailAddress) {
                return email.test(_emailAddress);
            },
            checkCardForm: function (_formData, _operation) {
                // bc_card_name
                /*if (_formData.bc_card_name) {
                 if (_formData.bc_card_name.length > 15) {
                 alertPopup = ionNative.popup().alert({
                 title: '名片名称不能超过15个字符！',
                 okText: '确认'
                 });
                 return false;
                 }
                 }*/

                // bc_mobile
                if (_formData.bc_mobile) {
                    if (!(this.isMobile(_formData.bc_mobile))) {
                        alertPopup = ionNative.popup().alert({
                            title: '手机号码格式不正确!',
                            okText: '确认'
                        });
                        return false;
                    }
                }

                // bc_telephone
                if (_formData.bc_telephone) {
                    if (!(telephone.test(_formData.bc_telephone))) {
                        alertPopup = ionNative.popup().alert({
                            title: '电话号码格式不正确!',
                            okText: '确认'
                        });
                        return false;
                    }
                }

                // bc_job_title            15
                if (_formData.bc_job_title) {
                    if (_formData.bc_job_title.length > 15) {
                        alertPopup = ionNative.popup().alert({
                            title: '职位名称不能超过15个字符!',
                            okText: '确认'
                        });
                        return false;
                    }
                }

                // bc_company              45
                if (_formData.bc_company) {
                    if (_formData.bc_company.length > 45) {
                        alertPopup = ionNative.popup().alert({
                            title: '公司名称不能超过45个字符!',
                            okText: '确认'
                        });
                        return false;
                    }
                }

                // bc_email_address
                if (_formData.bc_email_address) {
                    if (!(this.isEmail(_formData.bc_email_address))) {
                        alertPopup = ionNative.popup().alert({
                            title: '邮箱格式不正确!',
                            okText: '确认'
                        });
                        return false;
                    }
                }

                // bc_fax                  11
                if (_formData.bc_fax) {
                    if (!(fax.test(_formData.bc_fax))) {
                        alertPopup = ionNative.popup().alert({
                            title: '传真格式不正确!',
                            okText: '确认'
                        });
                        return false;
                    }
                }

                // bc_url                  45
                if (_formData.bc_url) {
                    if (_formData.bc_url.length > 45) {
                        alertPopup = ionNative.popup().alert({
                            title: '网址格式不正确!',
                            okText: '确认'
                        });
                        return false;
                    }
                }

                // bc_remarks              45
                if (_formData.bc_remarks) {
                    if (_formData.bc_remarks.length > 45) {
                        alertPopup = ionNative.popup().alert({
                            title: '备注内容不能超过45个字符!',
                            okText: '确认'
                        });
                        return false;
                    }
                }

                // bc_user_name            45
                if (_formData.bc_user_name) {
                    if (_formData.bc_user_name.length > 45) {
                        alertPopup = ionNative.popup().alert({
                            title: '用户姓名不能超过45个字符!',
                            okText: '确认'
                        });
                        return false;
                    }
                }

                // bc_company_address      45
                if (_formData.bc_company_address) {
                    if (_formData.bc_company_address.length > 45) {
                        alertPopup = ionNative.popup().alert({
                            title: '公司地址不能超过45个字符!',
                            okText: '确认'
                        });
                        return false;
                    }
                }

                // bc_card_intro      90
                if (_formData.bc_card_intro) {
                    if (_formData.bc_card_intro.length > 45) {
                        alertPopup = ionNative.popup().alert({
                            title: '名片简介不能超过45个字符!',
                            okText: '确认'
                        });
                        return false;
                    }
                }

                if (_operation === 'add') {
                    if (!_formData.bc_card_templet_id) {
                        alertPopup = ionNative.popup().alert({
                            title: '请选择名片模板!',
                            okText: '确认'
                        });
                        return false;
                    }

                    if (!_formData.bc_background_image_id) {
                        alertPopup = ionNative.popup().alert({
                            title: '请选择名片背景!',
                            okText: '确认'
                        });
                        return false;
                    }
                }

                return true;
            },
            checkMobile: function (_mobile) {
                if (_mobile) {
                    if (this.isMobile(_mobile)) {
                        return true;
                    } else {
                        ionNative.popup().alert({
                            title: '操作失败',
                            template: '请确认您的手机号码是否正确!',
                            okText: '确认'
                        });
                        return false;
                    }
                } else {
                    ionNative.popup().alert({
                        title: '操作失败',
                        template: '请输入您的手机号码！',
                        okText: '确认'
                    });
                    return false;
                }
            },
            checkPassword: function (_pwd) {
                if (_pwd !== undefined && _pwd.length >= 8) {
                    return true;
                } else {
                    ionNative.popup().alert({
                        title: '密码输入错误',
                        template: '密码由8位以上字符串、数字、下划线组成!',
                        okText: '确认'
                    });
                    return false;
                }
            },
            // 验证码检测
            checkCaptcha: function (_captcha) {
                var rep = /\d{6}/.test(_captcha);
                if (!(rep && _captcha.length === 6)) {
                    ionNative.popup().alert({
                        title: '验证码输入错误',
                        template: '请输入验证码，验证码由6位数字组成!',
                        okText: '确认'
                    });
                    return false;
                }
                return true;
            },
            // 90s 倒计时
            countDown: function (_data) {
                var second = 90,
                    timePromise = undefined;
                timePromise = $interval(function () {
                    if (second <= 0) {
                        $interval.cancel(timePromise);
                        timePromise = undefined;
                        second = 90;
                        _data.paracont = "重发验证码";
                        _data.paraclass = "button-energized";
                        _data.paraevent = true;
                    } else {
                        _data.paracont = second + "秒后可重发";
                        _data.paraclass = "button-stable";
                        _data.paraevent = false;
                        second--;
                    }
                }, 1000, 100);
            },
            Countdown2: function (scope, time) {
                var second = time,
                    timePromise = undefined;
                timePromise = $interval(function () {

                    if (second <= 0) {
                        $interval.cancel(timePromise);
                        timePromise = undefined;
                        second = 90;
                        scope.paracont = "重发验证码";
                        scope.paraclass = "button-energized";
                        scope.paraevent = true;
                    } else {
                        scope.paracont = second + "秒后可重发";
                        scope.paraclass = "button-stable";
                        scope.paraevent = false;
                        second--;
                    }

                }, 1000, 100);
            },
            /* 设置调用 AppKey */
            setAppKey: function (_appKey) {
                localStorage.setItem('appKey', _appKey);
            },
            getAppKey: function () {
                return localStorage.getItem('appKey');
            }
        }
    })
    .factory('HttpService', function ($q, $http, HostConfig) {
        var API = HostConfig.getAPI();
        return {
            get: function (url, params) {
                // return console.log(11111);
                var def = $q.defer();
                $http.get(API + url, {params: params}).then(function (response) {
                    // return console.log('状态码：'+JSON.stringify(response.data) );
                    if (response.data.code === 100) {
                        def.resolve(response.data.data);
                    } else {
                        def.resolve('error');
                        // Logger.error('出错了！错误代码（code）:' + response.data.code);
                    }
                }, function (error) {
                    def.reject(error);
                });
                // return console.log(def.promise);
                return def.promise;
            },
            post: function (url, body) {
                var def = $q.defer();
                $http.post(API + url, body).then(function (response) {
                    if (response.data.code === 100) {
                        def.resolve(response.data.data);
                    } else {
                        def.resolve('error');
                        // Logger.error('出错了！错误代码（code）:' + response.data.code);
                    }
                }, function (error) {
                    def.reject(error);
                });
                return def.promise;
            },
            put: function (url, body) {
                var def = $q.defer();
                $http.put(API + url, body).then(function (response) {
                    if (response.data.code === 100) {
                        def.resolve(response.data.data);
                    } else {
                        def.resolve('error');
                        // Logger.error('出错了！错误代码（code）:' + response.data.code);
                    }
                }, function (error) {
                    def.reject(error);
                });
                return def.promise;
            },
            delete: function (url, body) {
                var def = $q.defer();
                $http.delete(API + url, {data: body}).then(function (response) {
                    if (response.data.code === 100) {
                        def.resolve(response.data.data);
                    } else {
                        def.resolve('error');
                        // Logger.error('出错了！错误代码（code）:' + response.data.code);
                    }
                }, function (error) {
                    def.reject(error);
                });
                return def.promise;
            }
        }
    })
    //JWT
    .factory('HttpInterceptor', function ($q, $location, Storage, Logger) {
        var _interceptor = {
            'request': function (config) {
                config.headers = config.headers || {};
                config.headers['Content-Type'] = 'application/json;charset=UTF-8';

                if (config.url.indexOf('userController') !== -1) {
                    // config.headers.appKey = localStorage.getItem('appKey');
                    config.headers.appKey = '958ce0a62c344546a9111cbbfbf15c01'
                    // return console.log(localStorage.getItem('appKey'));//能取出存的appkey
                }
                // Logger.log(config.headers);
                // 成功的请求方法
                return config; // 或者 $q.when(config);
            },
            'response': function (response) { // 响应成功
                if (response.data.code === 103) {
                    $location.path('/login');
                    Storage.ls_delete('user_token');
                    Storage.ls_delete('user_id');
                    Storage.ls_delete('user_login_name');
                    Storage.ls_delete('user_name');
                    Storage.ls_delete('user_login_mobile');
                    Storage.ls_delete('user_login_time');
                    return $q.reject(response);
                }
                return response; // 或者 $q.when(config);
            },
            'requestError': function (rejection) {
                // 请求发生了错误，如果能从错误中恢复，可以返回一个新的请求或promise return response; // 或新的promise
                // 或者，可以通过返回一个rejection来阻止下一步
                return $q.reject(rejection);
            },
            'responseError': function (rejection) {
                // 请求发生了错误，如果能从错误中恢复，可以返回一个新的响应或promise return rejection; // 或新的promise
                // 或者，可以通过返回一个rejection来阻止下一步
                return $q.reject(rejection);
            }
        };
        return _interceptor;
    })
    .factory('Storage', function () {
        return {
            ls_set: function (_name, _data) {
                // 判断传入的数据是否为对象
                if (Object.prototype.toString.call(_data) === '[object Object]') {  
                    localStorage.setItem(_name, JSON.stringify(_data));
                } else {
                    localStorage.setItem(_name, _data);
                }
            },
            ls_get: function (_name) {
                return localStorage.getItem(_name);
            },
            ls_delete: function (_name) {
                localStorage.removeItem(_name);
            },
            ls_clean: function () {
                localStorage.clear()
            }
        }
    })
    .factory('JWT', function ($q, $http, HostConfig, jwtHelper) {

        // 获取登录时间
        function getLoginTime() {
            return localStorage.getItem('user_login_time');
        }

        // 获取 token 过期时间
        function getTokenExpirationDate(token) {
            var decoded = jwtHelper.decodeToken(token);
            if (typeof decoded.exp === "undefined") {
                return null;
            }
            var d = new Date(0); // The 0 here is the key, which sets the date to the epoch
            d.setUTCSeconds(decoded.exp);
            return d;
        }

        // 获取 token 生成时间
        function getTokenServeDate(token) {
            var decoded = jwtHelper.decodeToken(token);
            if (typeof decoded.iat === "undefined") {
                return null;
            }
            var d = new Date(0); // The 0 here is the key, which sets the date to the epoch
            d.setUTCSeconds(decoded.iat);
            return d;
        }

        // 设置 token
        function setJWT(token) {
            localStorage.setItem('user_login_time', new Date().getTime());
            localStorage.setItem('user_token', token);
        }

        function getJWT() {
            return localStorage.getItem('user_token');
        }

        function testJWT(token) {
            // 简单判断是否为 token， 判断字符串是否为三部分组成
            var parts = token.split('.');
            /*            if (parts.length !== 3) {
             return false;
             }
             return true;*/
            return parts.length === 3 ? true : false;
        }

        function refreshJWT() {
            // 重新请求 token
            var deferred = $q.defer();
            $http({
                method: 'GET',
                url: HostConfig.getAPI() + '/userController/refreshToken',
                skipAuthorization: true, // 这里要禁用 jwt
                headers: {
                    'Content-Type': 'application/json',
                    'jwt': this.getJwt() // 传参 jwt
                }
            }).success(function (success) {
                deferred.resolve(success);
            }).error(function (error) {
                deferred.reject(error);
            });
            return deferred.promise;
        }

        function isTokenExpired(_token, _offsetSeconds) {
            var generateTime = getTokenServeDate(_token).valueOf(); // token 生成时间
            var expirationTime = getTokenExpirationDate(_token).valueOf(); // token 过期时间
            var signInTime = parseInt(getLoginTime()); // 登录时间
            var currentTime = new Date().valueOf(); // 当前时间
            var diff = signInTime - generateTime; // 计算 C/S 时间的差值
            var offsetSeconds = _offsetSeconds || 0;
            if (generateTime === null) {
                return false;
            }
            if (expirationTime === null) {
                return false;
            }
            if (signInTime === null || signInTime === undefined) {
                return false;
            }
            // Token expired?
            if (signInTime !== generateTime) {
                return !(expirationTime > ((currentTime - diff) + (offsetSeconds * 1000)));
            } else {
                return !(expirationTime > (currentTime + (offsetSeconds * 1000)));
            }
        }

        return {
            setJwt: setJWT,
            getJwt: getJWT,
            testJwt: testJWT,
            refreshJwt: refreshJWT,
            isTokenExpired: isTokenExpired,
            skipAuth: function (name) {
                /* 是否为 sign 页面 */
                switch (name) {
                    case 'login':
                    case 'register':
                    case 'getPwd':
                        return true;
                        break;
                    default:
                        return false;
                        break;
                }
            },

            checkJwt: function (token, offsetSeconds) {
                /* token 存在且格式正确且未过期 */
                var _offsetSeconds = offsetSeconds || 0;
                return token && testJWT(token) && !isTokenExpired(token, offsetSeconds);
            }
        }
    })
    //是否进入启动页
    .factory('Start', function () {

        function get() {
            /* get */
            return localStorage.getItem('isStart');
        }

        function set(value) {
            /* set */
            localStorage.setItem('isStart', value);
        }

        return {
            setStart: set,
            getStart: get,
            isStart: function () {
                /* 是否启动 */
                return get();
            }
        }
    })

     // .factory(' ', function ($ionicPopup, $ionicLoading,
    //                                 $cordovaAppVersion, $cordovaNetwork, $cordovaBarcodeScanner, $cordovaCamera,
    //                                 $cordovaFileTransfer, $cordovaToast, $cordovaInAppBrowser, $cordovaSms, $cordovaContacts) {
       .factory('ionNative', function ($ionicPopup, $ionicLoading) {
        /* ionic components */
        function popup() {
            var $popup = $ionicPopup;
            // 弹窗
            return {
                alert: function (options) {
                    return $popup.alert(options);
                },
                confirm: function (options) {
                    return $popup.confirm(options);
                },
                show: function (options) {
                    return $popup.show(options);
                },
                prompt: function (options) {
                    return $popup.prompt(options);
                }
            }
        }

        function loading() {
            var $loading = $ionicLoading;
            // 遮罩
            return {
                show: function (options) {
                    return $loading.show({
                        template: options.template,             // 指示器的html内容。
                        templateUrl: options.templateUrl,       // 一个加载html模板的url作为指示器的内容。
                        noBackdrop: options.noBackdrop,         // 是否隐藏背景。默认情况下它会显示。
                        delay: options.delay,                   // 指示器延迟多少毫秒显示。默认为不延迟。
                        duration: options.duration              // 等待多少毫秒后自动隐藏指示器。默认情况下，指示器会一直显示，直到触发.hide()。
                    })
                },
                hide: function () {
                    return $loading.hide();
                }
            }
        }

        /* cordova plugins */

        // function platform() {
        //     var ionicPlatform = ionic.Platform;
        //     return {
        //         isIOS: function () {
        //             return ionicPlatform.isIOS();
        //         },
        //         isAndroid: function () {
        //             return ionicPlatform.isAndroid();
        //         },
        //         platform: function () {
        //             return ionicPlatform.platform();
        //         }
        //     }
        // }

        // function network() {
        //     var network = $cordovaNetwork;
        //     return {
        //         getNetwork: function () {
        //             return network.getNetwork();
        //         },
        //         isOffline: function () {
        //             return network.isOffline();
        //         }
        //     }
        // }

        function toast() {
            var $toast = $cordovaToast;
            return {
                shortTop: function (message) {
                    return $toast.showShortTop(message);
                },
                shortCenter: function (message) {
                    return $toast.showShortCenter(message);
                },
                longTop: function (message) {
                    return $toast.showLongTop(message);
                },
                longCenter: function (message) {
                    return $toast.showLongCenter(message);
                }
            }
        }

        // function camera() {
        //     var $camera = $cordovaCamera;
        //     return {
        //         getPictures: function (options) {
        //             return $camera.getPicture(options);
        //         },
        //         cleanup: function () {
        //             return $camera.cleanup();
        //         }
        //     }
        // }

        // function contacts() {
        //     var $contacts = $cordovaContacts;
        //     return {
        //         find: function (options) {
        //             return $contacts.find(options);
        //         }
        //     }
        // }

        // function appVersion() {
        //     var $app = $cordovaAppVersion;
        //     return {
        //         versionNumber: function () {
        //             return $app.getVersionNumber();
        //         }
        //     }
        // }

        return {
            // platform: platform,
            popup: popup,
            loading: loading,
            toast: toast,
            // network: network,
            // camera: camera,
            // contacts: contacts,
            // appVersion: appVersion,

            // scan: function (options) {
            //     return $cordovaBarcodeScanner.scan(options);
            // },
            // download: function (source, filePath, options, trustAllHosts) {
            //     return $cordovaFileTransfer.download(source, filePath, options, trustAllHosts);
            // },
            // open: function (url, target, requestOptions) {
            //     return $cordovaInAppBrowser.open(url, target, requestOptions);
            // },
            // sms: function (number, message, options) {
            //     return $cordovaSms.send(number, message, options);
            // }
        }
    })
    //APP更新服务
    .factory('AppUpdate', function ($q, $http, $cordovaFileOpener2, $timeout, $window, HostConfig, ionNative, Common) {
        var platform = ionNative.platform().platform();

        // 判断下载
        function updateDownload() {
            if (platform === 'android') {
                UpdateForAndroid(); // 可以追加 downloadUrl 参数
            }
            if (platform === 'ios') {
                UpdateForIOS();
            }
        }

        // android 下载
        function UpdateForAndroid(downloadUrl) {
            console.log('UpdateForAndroid');
            $window.open('https://www.kakanet.net');
            
            // var source = downloadUrl || 'https://www.kakanet.net/kaka.apk',
            //     filePath = "/sdcard/Download/kaka.apk",
            //     options = {},
            //     trustHosts = true;
            // ionNative.loading().show({
            //     template: "已经下载：0%"
            // });
            // ionNative
            //     .download(source, filePath, options, trustHosts)
            //     .then(function (result) {
            //         return $cordovaFileOpener2.open(filePath, 'application/vnd.android.package-archive');
            //     }, function (error) {
            //         ionNative.loading().show({
            //             template: "下载失败"
            //         });
            //         ionNative.loading().hide();
            //     }, function (progress) {
            //         $timeout(function () {
            //             var downloadProgress = (progress.loaded / progress.total) * 100;
            //             ionNative.loading().show({
            //                 template: "已经下载：" + Math.floor(downloadProgress) + "%"
            //             });
            //             if (downloadProgress > 99) {
            //                 ionNative.loading().hide();
            //             }
            //         });
            //     })
            //     .then(function (res) {
            //         // 成功
            //         ionNative.loading().hide();
            //     });
        }

        // ios 下载
        function UpdateForIOS() {
            console.log('UpdateForIOS');
            $window.open('itms-apps://itunes.apple.com/us/app/kaka%E5%90%8D%E7%89%87/id1218096159?l=zh&ls=1&mt=8');
        }

        function compareVersion(latestV, clientV, isTrue) {
            var l = latestV.split('.'),
                c = clientV.split('.'),
                networkType = ionNative.network().getNetwork(),
                _popup = {};

            if (l[0] === c[0] && l[1] === c[1] && l[2] === c[2]) {
                // 最新版本，不需要更新
                if (isTrue) {
                    if (platform === 'android') {
                        ionNative.popup().alert({
                            title: '版本提示',
                            template: '当前版本为最新版本',
                            okText: '确定'
                        });
                    }
                }
            } else {

                if (l[0] > c[0]) {
                    // 强制更新
                    _popup = {
                        title: '发现新版本',
                        template: '该版本过低，将影响使用，请立即更新',
                        okText: '立即更新'
                    };
                    ionNative.popup().alert(_popup).then(function (res) {
                        updateDownload();
                    });
                }

                if (l[1] > c[1] || l[2] > c[2]) {
                    // 普通更新
                    _popup = {
                        template: '立即更新到最新版本',
                        okText: '更新',
                        cancelText: '忽略'
                    };
                    if (networkType === 'wifi') {
                        _popup.title = '发现新版本'
                    } else {
                        _popup.title = '发现新版本（建议WIFI下升级）';
                    }
                    ionNative.popup().confirm(_popup).then(function (res) {
                        if (res) {
                            updateDownload();
                        }
                    })
                }
            }
        }


        function get_app_version(_platform) {//服务器端获取APP里面最新的版本
            var deferred = $q.defer();
            $http({
                method: 'GET',
                url: HostConfig.getAPI() + '/userController/versionCheck',
                params: {
                    platform: _platform // 应用平台信息
                },
                headers: {
                    'Content-Type': 'application/json',
                    // 'appKey': Common.getAppKey()
                }
            }).success(function (success) {
                if (success.code === 100) {
                    deferred.resolve(success.data);
                }
            }).error(function (error) {
                deferred.reject(error);
            });
            return deferred.promise;
        }

        return {
            checkAppVersion: function (scope, isTrue) {
                var deferred = $q.defer(),
                    latest,
                    client;
                ionNative.appVersion().versionNumber().then(function (client_version) {
                    client = client_version; // 当前 app version
                    return get_app_version(platform);
                }).then(function (response) {
                        latest = response.current_version; // 最新 app version
                        compareVersion(latest, client, isTrue);

                        deferred.resolve(response);
                    },
                    function (error) {
                        deferred.reject(null);
                    });
            }
        }
    })

    

    

